package com.tgy.crud.service.impl;

import com.tgy.crud.common.ResultCode;
import com.tgy.crud.domain.Person;
import com.tgy.crud.exception.CrudException;
import com.tgy.crud.mapper.PersonMapper;
import com.tgy.crud.service.PersonService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonMapper personMapper;


    @Transactional(rollbackFor = SQLException.class)
    @Override
    public int insertPerson(Person person) throws SQLException {

        int count = personMapper.insertPerson(person);

        if (count == 1){

            throw new SQLException("ads");
        }
        return count;
    }

//    @Cacheable(cacheNames = "person",key = "'person'+#id")
    @Cacheable(cacheNames = "person",keyGenerator = "personKeyGenerator")
    @Transactional(readOnly = true)
    @Override
    public Person findPersonById(Integer id) {

        return personMapper.findPersonById(id);
    }

//    @CacheEvict(cacheNames = "person",key = "'person' + #person.id")
    @CacheEvict(cacheNames = "person",keyGenerator = "personKeyGenerator")
    @Transactional
    @Override
    public int updatePerson(Person person) {

        if (person.getId() == null){

            throw new CrudException(ResultCode.VALIDATE_FAILED,"person id 为空");
        }
        return personMapper.updatePerson(person);
    }

    @CacheEvict(cacheNames = "person",keyGenerator = "personKeyGenerator")
    @Transactional
    @Override
    public int deletePersonById(Integer id) {

        personMapper.deletePersonById(id);
        Person person = new Person("田七", 24, 1,"嘿嘿");
        try {

//            this.insertPerson(person);
            // 要使用AopContext 获取currentProxy。必须开启 @EnableAspectJAutoProxy(proxyTargetClass = true,exposeProxy = true)，同时导入aspectj的jar包
            PersonService currentProxy = (PersonService)AopContext.currentProxy();
            currentProxy.insertPerson(person);

        } catch (SQLException e) {
            e.printStackTrace();
//            throw new CrudException(ResultCode.FORBIDDEN);
        }

        return 1;
    }
}
